﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/**
 * 创建时间：2014/12/15 14:53:13
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.Common
{
    public class IsolatedStorageSettingHelper
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <returns>Is Add</returns>
        public static bool AddIsolateStorageFromObject(string key, object value)
        {
            bool isAdd = false;
            if (!string.IsNullOrEmpty(key) && value != null)
            {
                IsolatedStorageSettings.ApplicationSettings[key] = value;
                IsolatedStorageSettings.ApplicationSettings.Save();
                isAdd = true;
            }
            return isAdd;
        }


        /// <summary>
        /// 获取IsolateStorage并转换为String
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns>String Format</returns>
        public static string GetIsolateStorageToString(string key)
        {
            string storeStr = string.Empty;
            if (!string.IsNullOrEmpty(key))
            {
                if (IsolateStorageKeyIsExist(key))
                    storeStr = IsolatedStorageSettings.ApplicationSettings[key].ToString();
            }
            return storeStr;
        }


        /// <summary>
        /// 获取IsolateStorage并转换为Object
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns>object Format</returns>
        public static object GetIsolateStorageToObject(string key)
        {
            object storeObj = null;
            if (!string.IsNullOrEmpty(key))
            {
                if (IsolateStorageKeyIsExist(key))
                    storeObj = IsolatedStorageSettings.ApplicationSettings[key];
            }
            return storeObj;
        }


        /// <summary>
        /// IsolateStorage是否存在
        /// </summary>
        /// <param name="key">Storage Key</param>
        /// <returns>Is Exists</returns>
        public static bool IsolateStorageKeyIsExist(string key)
        {
            bool isExist = false;
            if (!string.IsNullOrEmpty(key))
            {
                foreach (string currentkey in IsolatedStorageSettings.ApplicationSettings.Keys)
                {
                    if (currentkey.Equals(key))
                    {
                        isExist = true;
                        break;
                    }
                }
            }
            return isExist;
        }


        /// <summary>
        /// 移除IsolateStorage
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns>Is Remove</returns>
        public static bool RemoveIsolateStorageByKey(string key)
        {
            bool IsRemove = false;
            if (!string.IsNullOrEmpty(key))
            {
                IsolatedStorageSettings.ApplicationSettings.Remove(key);
                IsolatedStorageSettings.ApplicationSettings.Save();
                IsRemove = true;
            }
            return IsRemove;
        }

        /// <summary>
        /// 获取此应用缓存数据大小
        /// </summary>
        /// <returns></returns>
        public static double GetCacheSize()
        {
            long cacheSize = 0L;
            try
            {
                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isolatedStorageFile.DirectoryExists(KEYS.ComicIslandCacheDirectory))
                    {
                        isolatedStorageFile.Dispose();
                        return 0;
                    }

                    //指定目录下的子目录
                    //var list = isolatedStorageFile.GetDirectoryNames(System.IO.Path.Combine(Keys.MediabrisCacheDirectory, "*"));
                    //因为只有一级目录，所以没有子目录
                    //指定目录下的文件列表
                    var files = isolatedStorageFile.GetFileNames(Path.Combine(KEYS.ComicIslandCacheDirectory, "*"));
                    foreach (string filename in files)
                    {
                        string filepath = Path.Combine(KEYS.ComicIslandCacheDirectory, filename);
                        if (!isolatedStorageFile.FileExists(filepath))
                            continue;
                        using (IsolatedStorageFileStream stream = isolatedStorageFile.OpenFile(filepath, FileMode.Open, FileAccess.Read))
                        {
                            cacheSize += stream.Length;//返回大B
                            stream.Close();
                            stream.Dispose();
                        }
                    }

                    isolatedStorageFile.Dispose();
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError("计算缓存大小异常" + Environment.NewLine + err.Message, typeof(IsolatedStorageSettingHelper), MethodBase.GetCurrentMethod());
            }

            if (cacheSize > 0)
            {
                return Math.Round(((cacheSize / 1024.0000) / 1024.0000), 2);
            }
            return cacheSize;
        }

        /// <summary>
        /// 移除所有缓存信息
        /// </summary>
        public static void RemoveIsolateStorageByAll()
        {
            try
            {
                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isolatedStorageFile.DirectoryExists(KEYS.ComicIslandCacheDirectory))
                    {
                        //指定目录下的子目录
                        //var list = isolatedStorageFile.GetDirectoryNames(System.IO.Path.Combine(Keys.MediabrisCacheDirectory, "*"));
                        //指定目录下的文件列表
                        var files = isolatedStorageFile.GetFileNames(Path.Combine(KEYS.ComicIslandCacheDirectory, "*"));
                        foreach (string filename in files)
                        {
                            string filepath = Path.Combine(KEYS.ComicIslandCacheDirectory, filename);
                            if (isolatedStorageFile.FileExists(filepath))
                            {
                                isolatedStorageFile.DeleteFile(filepath);
                            }
                        }
                        //这个目录不能删除
                        //isolatedStorageFile.DeleteDirectory(KEYS.ComicIslandCacheDirectory);
                    }
                    isolatedStorageFile.Dispose();
                }
                //
                //IsolatedStorageSettings.ApplicationSettings.Clear();
            }
            catch (Exception err)
            {
                LogHelper.LogError("清理缓存异常" + Environment.NewLine + err.Message, typeof(IsolatedStorageSettingHelper), MethodBase.GetCurrentMethod());
            }
        }

    }
}
